/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lotus.tep.ui;

import com.lotus.tep.constant.FrameUiConstant;
import com.lotus.tep.constant.VoiceUiConstant;
import com.lotus.tep.constant.WebBrowserUiConstant;
import com.lotus.tep.event.DefaultWebBrowserHandler;
import com.lotus.tep.event.VoiceUiHandler;
import com.lotus.tep.trouble.BrowserListenerException;
import com.lotus.tep.trouble.VoiceUiException;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;

/**
 *
 * @author arvind.sharma
 */
public class FrameUi {

	private final JFrame jFrame_;

	private FrameUi(String title) {
		jFrame_ = new JFrame(title);
	}

	public static FrameUi createBrowserUi() {
		FrameUi browserUi = new FrameUi(FrameUiConstant.BROWSER_TITLE);
		browserUi.setFrameDefaults();
		browserUi.addComponents();
		browserUi.jFrame_.setVisible(true);
		return browserUi;
	}

	private void setFrameDefaults() {
		jFrame_.setLocationByPlatform(true);
		jFrame_.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Dimension d = getDimensionAsPerScreen();
		jFrame_.setPreferredSize(d);
		jFrame_.setSize(d);
		jFrame_.setExtendedState(JFrame.MAXIMIZED_BOTH);
	}

	private Dimension getDimensionAsPerScreen() {
		Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
		dimension.width -= FrameUiConstant.BROWSER_SCREEN_HORIZONTAL_GAP;
		dimension.height -= FrameUiConstant.BROWSER_SCREEN_VERTICAL_GAP;
		return dimension;
	}

	private void addComponents() {
		VoiceUi voiceUi = VoiceUi.createVoiceUi();
		jFrame_.add(voiceUi.getComponent(), FrameUiConstant.VOICE_UI_LOCATION);
		WebBrowserUi browserUi = WebBrowserUi.createWebBrowserUi();
		jFrame_.add(browserUi.getComponent());
		addListeners(voiceUi, browserUi);
	}

	private void addListeners(VoiceUi voiceUi, WebBrowserUi browserUi) {
		VoiceUiHandler uiHandler = null;
		try {
			uiHandler = VoiceUiHandler.createVoiceControlHandler(voiceUi);
		} catch (VoiceUiException ex) {
			MessageUi.error(null, VoiceUiConstant.LISTENER_EXCEPTION_USER_MSG);
		}
		try {
			browserUi.registerWebBrowserListener(DefaultWebBrowserHandler.createDefaultWebBrowserHandler(uiHandler, voiceUi));
		} catch (BrowserListenerException ex) {
			MessageUi.error(null, WebBrowserUiConstant.BROWSER_LISTENER_EXCEPTION_USER_MSG);
		}
	}
}
